package com.xinqi.gateway.filter;

import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.utils.json.JSON;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.gateway.utils.WebFluxUtils;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * 防止重复调用拦截器，通过 header 中的 sa-repeat-call 判断是否重复调用
 *
 * @author linkai
 */
@Component
@RequiredArgsConstructor
public class RepeatCallAuthFilter implements GlobalFilter, Ordered {
    private static final String REPEAT_CALL_HEAD = "sa-repeat-call";
    private static final String REPEAT_CALL_KEY = "repeat:call:%s";
    private static final Duration REPEAT_CALL_EXPIRE = Duration.ofSeconds(10);
    private final RedissonClient client;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 如果请求头中包含 sa-repeat-call，则判断 redis 中是否存在，如果存在则返回 429，如果不存在则添加到 redis 中
        if (request.getHeaders().containsKey(REPEAT_CALL_HEAD)) {
            String repeatCall = request.getHeaders().getFirst(REPEAT_CALL_HEAD);
            if (StringUtils.isNotEmpty(repeatCall) &&
                !client.getBucket(String.format(REPEAT_CALL_KEY, repeatCall)).setIfAbsent("1", REPEAT_CALL_EXPIRE)) {
                return WebFluxUtils.webFluxResponseWriter(
                    exchange.getResponse(),
                    JSON.stringify(CommonErrors.BAD_REQUEST.withMessage("重复调用").asResult())
                );
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -200;
    }

}

